/* 
 * File:   StorageRule.h
 * Author: jeffrey
 *
 * Created on May 19, 2010, 5:27 PM
 *
 * Store a pointer to a derivation
 */

#ifndef _STORAGERULE_H
#define	_STORAGERULE_H
#include <iostream>
#include "Section.h"
#include "Derivation.h"
#include "DMLStatement.h"

class StorageRule {
public:
    StorageRule();
    StorageRule(const StorageRule& orig);
    virtual ~StorageRule();
    friend ostream & operator<<(ostream&, const StorageRule&);
    void setTerminalDerivation(Derivation& d);
    void loadTerminalDerivation(Derivation& d);
    void addPSQL(string psql); // Create a Parameterized SQL object from string
    void deletePSQL(int entryNo);
    void print();
    void buildFile(string filename);
    string getId();
    void parameterize();

    vector<DMLStatement> getSQL();
private:
    Derivation deriv;
    Section<DMLStatement> psqlsec;

};

StorageRule::StorageRule() {
}

StorageRule::StorageRule(const StorageRule& orig) {
    deriv = orig.deriv;
    psqlsec = orig.psqlsec;

}

StorageRule::~StorageRule() {
}

ostream & operator<<(ostream& output, const StorageRule& data) {
    //string o;
    //o = data.getString();
    return output << data.deriv.getString();
}

//TODO: make one nice procedure for both version f setTerminalDerivation
void StorageRule::setTerminalDerivation(Derivation& d) {
    if (d.isTerminal()) {
        d.parameterize();
        deriv = d;
    } else {
        cerr << d << ": Terminating derivations contains non-terminal" << endl;
    }

}

void StorageRule::loadTerminalDerivation(Derivation& d) {
        deriv = d;
}

void StorageRule::addPSQL(string psql) {
    DMLStatement p; //
    bool psqlok;
    psqlok = p.addPStatement(psql);
    if (psqlok) {
        psqlsec.add(p);
    } else {
        cerr << psql << ": Not a valid parameterized SQL statement" << endl;
    }

}

void StorageRule::deletePSQL(int entryNo) {
    psqlsec.remove(entryNo);
}

void StorageRule::print() {

    cout << ".STRUCT" << endl;
    cout << "REF:" << deriv << endl;
    psqlsec.print();
    cout << ".END_STRUCT" << endl;
}

void StorageRule::buildFile(string filename) {

    std::ofstream myfile(filename.c_str(), std::ios::app);
    myfile << ".STRUCT" << "\n";
    myfile << "REF:" << deriv << "\n";
    myfile.close();
    psqlsec.buildFile(filename);
    myfile.open(filename.c_str(), std::ios::app);
    myfile << ".END_STRUCT" << "\n";
}

string StorageRule::getId() {
    return deriv.getString();
}

void StorageRule::parameterize(){
    deriv.parameterize();
}

vector<DMLStatement> StorageRule::getSQL()
{
   
    return psqlsec.getSectionData();
}



#endif	/* _STORAGERULE_H */

